package ar.com.mooral.activities;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Vector;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import ar.com.mooral.crohn.application.CrohnContext;
import ar.com.mooral.crohn.view.CrohnButton;
import ar.com.mooral.crohn.view.CrohnImageView;
import ar.com.mooral.data.DatabaseHelper;
import ar.com.mooral.data.Depositions;
import ar.com.mooral.data.Foods;
import ar.com.mooral.data.GeneralStatus;
import ar.com.mooral.data.MissedMedications;
import ar.com.mooral.data.Pain;
import ar.com.mooral.data.PatientSymptoms;
import ar.com.mooral.data.SexualActivityIncidence;
import ar.com.mooral.data.SocialActivityIncidence;
import ar.com.mooral.data.WorkActivityIncidence;
import ar.com.mooral.pojo.BasePojo;
import ar.com.mooral.pojo.util.PojoComparatorDate;


public class Registros extends CrohnActivity{

	private Context context;
	
	private Vector<CrohnImageView> deleteImageViews;

	protected void onRestart() {
		super.onRestart();
		
        String lastChoise = CrohnContext.getRecordsSelectedChoise();
        if (lastChoise == null) {
        	lastChoise = "ALL";
        }
        
		draw(lastChoise);
	}

	
	protected void onStart() {
		super.onStart();
		
        String lastChoise = CrohnContext.getRecordsSelectedChoise();
        if (lastChoise == null) {
        	lastChoise = "ALL";
        }
        
		draw(lastChoise);
	}
	
	
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.registros);
        
        this.context = this;
        

        // EDITAR
        ((TextView)findViewById(R.id.lblRegistrosEditar)).setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		    	for (ImageView img : deleteImageViews ) {
		    		img.setVisibility((img.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE));
		        }
		    }
        });
        
        
        
        // ALL
        ((Button)findViewById(R.id.btnRegistrosTodos)).setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		    	draw("ALL");
		    	CrohnContext.setRecordsSelectedChoise("ALL");
		    }
        });

        
        
        // DEPOSITIONS
        ((Button) findViewById(R.id.btnRegistrosDeposiciones)).setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		        draw("DEP");
		        CrohnContext.setRecordsSelectedChoise("DEP");
		    }
        });


        // FOODS
        ((Button) findViewById(R.id.btnRegistrosAlimentacion)).setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		        draw("COM");
		        CrohnContext.setRecordsSelectedChoise("COM");
		    }
        });
        
        
        
        // GENERAL STATUS
        ((Button) findViewById(R.id.btnRegistrosEstadoGeneral)).setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		        draw("EGE");
		        CrohnContext.setRecordsSelectedChoise("EGE");
		    }
        });
        
        
        // MISSED MEDICATION
        ((Button) findViewById(R.id.btnRegistrosMedicacionPerdida)).setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		        draw("MPE");
		        CrohnContext.setRecordsSelectedChoise("MPE");
		    }
        });

        
        // PAIN
        ((Button) findViewById(R.id.btnRegistrosDolorAbdominal)).setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		        draw("DOL");
		        CrohnContext.setRecordsSelectedChoise("DOL");
		    }
        });
        

        // SINTOMAS PERSONALIZADOS
        ((Button) findViewById(R.id.btnRegistrosSintomasPersonalizados)).setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		        draw("SPA");
		        CrohnContext.setRecordsSelectedChoise("SPA");
		    }
        });

        
        // Actividad Sexual
        ((Button) findViewById(R.id.btnRegistrosActividadSexual)).setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		        draw("IAX");
		        CrohnContext.setRecordsSelectedChoise("IAX");
		    }
        });
        
        
        // Actividad social
        ((Button) findViewById(R.id.btnRegistrosActividadSocial)).setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		        draw("IAS");
		        CrohnContext.setRecordsSelectedChoise("IAS");
		    }
        });

        
        // Actividad Laboral
        ((Button) findViewById(R.id.btnRegistrosActividadLaboral)).setOnClickListener(new View.OnClickListener() {
		    public void onClick(View view) {
		        draw("IAL");
		        CrohnContext.setRecordsSelectedChoise("IAL");
		    }
        });
    }

    
	private void draw(String what) {
		
		
		if (this.getParent() != null && this.getParent().getClass().toString().equals("class ar.com.mooral.activities.TabRegistros")) {
			SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
			String today = formatter.format(new Date(System.currentTimeMillis()));
	
			CrohnContext.setRecordsMinRange(today + " 00:00:00");
			CrohnContext.setRecordsMaxRange(today + " 23:59:59");
		}
		
		
        String minRange = (CrohnContext.getRecordsMinRange()!=null?CrohnContext.getRecordsMinRange():CrohnContext.getDateTimeNow());
        String maxRange = (CrohnContext.getRecordsMaxRange()!=null?CrohnContext.getRecordsMaxRange():CrohnContext.getDateNow());
        

	    DatabaseHelper dbs[] = new DatabaseHelper[] {
				new Depositions(this.context),
				new Foods(this.context),
				new GeneralStatus(this.context),
				new MissedMedications(this.context),
				new Pain(this.context),
				new PatientSymptoms(this.context),
				new SexualActivityIncidence(this.context),
				new SocialActivityIncidence(this.context),
				new WorkActivityIncidence(this.context),
	        };

	    
		Vector<Hashtable<String, String>> data = new Vector<Hashtable<String, String>>();
	    if (what.equals("ALL")) {
		    for (int i = 0; i < dbs.length; i++) {
		    	data.addAll(dbs[i].findAll(minRange, maxRange));
		    }
	    } else {
		    for (int i = 0; i < dbs.length; i++) {
		    	if (what.equals(dbs[i].getShortTableName())) {
		    		data = dbs[i].findAll(minRange, maxRange);
		    		break;
		    	}
		    }
	    }
	    
	    drawGrid(data);
	}
	
    
    private void drawGrid(Vector data) {
    	
    	// Clean before addings
        LinearLayout records = (LinearLayout)findViewById(R.id.linearLayoutRegistros);
        records.removeAllViews();
        
        
        Collections.sort((Vector<BasePojo>)data, new PojoComparatorDate());
        
        deleteImageViews = new Vector<CrohnImageView>();
        
        for (int i = 0; i < data.size(); i++) {

	        BasePojo record = (BasePojo) data.get(i);
	        
			/*
			LinearLayout ll = new LinearLayout(this);
			ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			ll.setOrientation(LinearLayout.HORIZONTAL);
			ll.setPadding(5, 5, 5, 5);
			ll.setGravity(Gravity.CENTER_VERTICAL);
			records.addView(ll);
			*/
			
			LinearLayout ll = new LinearLayout(this);
			ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 45));
			ll.setOrientation(LinearLayout.HORIZONTAL);
			ll.setBackgroundResource(R.drawable.medication_bg);
			ll.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
			records.addView(ll);			
			

			CrohnImageView deleteImageView = new CrohnImageView(this);
			deleteImageView.setBackgroundResource(R.drawable.stop);
			deleteImageView.setLayoutParams(new LayoutParams(20, 20));
			deleteImageView.setVisibility(View.GONE);
			deleteImageView.setPojo(record);
			deleteImageView.setOnClickListener(new View.OnClickListener() {
    		    public void onClick(View view) {
    		    	BasePojo basePojo = ((CrohnImageView) view).getPojo();
    		    	basePojo.getDatabaseHelper().delete(basePojo.getId());
    		    	((LinearLayout) view.getParent().getParent()).removeView((View) view.getParent());
    		    }
            });
			deleteImageViews.add(deleteImageView);
			ll.addView(deleteImageView);
			

			
			CrohnButton recordButton = new CrohnButton(this);
			String text = record.getDate() + " - " + record.getName();
			if(text.length()>35) text = text.substring(0,35) + "...";
			recordButton.setText(text);
			//recordButton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			recordButton.setLayoutParams(new LayoutParams(280, 30));
			recordButton.setBackgroundResource(R.drawable.white);
			recordButton.setTextSize(10);
			recordButton.setPojo(record);
			recordButton.setOnClickListener(new View.OnClickListener() {
    		    public void onClick(View view) {
    		    	
    		    	BasePojo basePojo = ((CrohnButton) view).getPojo();
		    		CrohnContext.setPojo(basePojo);
    		    	
					Intent intent = new Intent();
					
					String tableIdentifier = basePojo.getDatabaseHelper().getShortTableName();
					if (tableIdentifier.equals("DOL")) {
    					intent.setComponent(new ComponentName(DolorAbdominal.class.getPackage().getName(), DolorAbdominal.class.getName()));
    		    	} else if (tableIdentifier.equals("EGE")) {
    		    		intent.setComponent(new ComponentName(EstadoGeneral.class.getPackage().getName(), EstadoGeneral.class.getName()));
    		    	} else if (tableIdentifier.equals("COM")) {
    		    		intent.setComponent(new ComponentName(Alimentacion.class.getPackage().getName(), Alimentacion.class.getName()));
    		    	} else if (tableIdentifier.equals("SPA")) {
    		    		intent.setComponent(new ComponentName(SintomaPersonalizado.class.getPackage().getName(), SintomaPersonalizado.class.getName()));
    		    	} else if (tableIdentifier.equals("DEP")) {
    		    		intent.setComponent(new ComponentName(Deposiciones.class.getPackage().getName(), Deposiciones.class.getName()));
    		    	} else if (tableIdentifier.equals("MPE")) {
    		    		intent.setComponent(new ComponentName(MedicacionPerdida.class.getPackage().getName(), MedicacionPerdida.class.getName()));
    		    	} else if (tableIdentifier.equals("IAX")) {
    		    		intent.setComponent(new ComponentName(ActividadSexual.class.getPackage().getName(), ActividadSexual.class.getName()));
    		    	} else if (tableIdentifier.equals("IAS")) {
    		    		intent.setComponent(new ComponentName(ActividadSocial.class.getPackage().getName(), ActividadSocial.class.getName()));
    		    	} else if (tableIdentifier.equals("IAL")) {
    		    		intent.setComponent(new ComponentName(ActividadLaboral.class.getPackage().getName(), ActividadLaboral.class.getName()));
    		    	}
					
    		    	
					//startActivity(intent);
	         		TabGroupActivity parentActivity = (TabGroupActivity)getParent();
	         		parentActivity.startChildActivity(tableIdentifier, intent);
					
    		    }
            });
			ll.addView(recordButton);
		    	
        } // for
    	
    }
}
